
# -*- coding: UTF-8 -*-
import urllib.request
import os
import re
from mz_decode import jandan_load_img


config={
    "folder":"./mm",
    "pages":3,
    "url":"http://jandan.net/ooxx/"
}


# 获取url 响应的内容
def getUrlContent(url,isDecode=False):
    
    req= urllib.request.Request(url);
    req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")

    try:
        res= urllib.request.urlopen(url)

        print(res.read())
        
        return res.read().decode("utf-8") if(isDecode) else res.read() 

    except urllib.error.HTTPError as e:
        print("发生错误了",e.reason)



# 获取最新的页码URl
def getPageUrl(page):
    
    html = getUrlContent(config["url"],True)

    currentPage = re.findall(r"<span class=\"current-comment-page\"\>\[(.+)\]",html)

    return config["url"]+"page-"+str(int(currentPage[0])-page)+"#comments"


# 获取页面的照片
def getPagePicture(page):
    
    html = getUrlContent(getPageUrl(page),True)

    imgArr=re.findall(r'<span class="img-hash">(.+)</span>',html)

    for i,val in enumerate(imgArr):
        imgArr[i]= "http:"+jandan_load_img(val)

    return imgArr


# 保存图片
def saveImg(img_arr):
    
    print("一共"+str(len(img_arr))+"张图片\n")

    for i in img_arr:
        filename = i.split("/")[-1]

        with open(filename,"wb") as f:
            img = getUrlContent(i)
            f.write(img) 

    print("下载完成!!!!!!!\n\n")


# 下载主函数
def download_mm():

    os.chdir(config["folder"])

    arr = range(config["pages"])
    
    for i in arr:
        
        print("开始下载第"+str(i+1)+"页的妹子\n")
        saveImg(getPagePicture(i))
    
    
    print("一共"+str(len(arr))+"页妹子被你下完了\n")

download_mm()


    
    
    
